from .views import *

# 地区订单查询
class RegionOrderSearch(APIView):
    def post(self, request):
        res = {}
        print(request.data)
        # 根据起止位置获取id
        start = request.data.get('start')
        end = request.data.get('end')
        start_id = Region.objects.filter(code=start[1], upgrade=start[0]).first().id
        end_id = Region.objects.filter(code=end[1], upgrade=end[0]).first().id
        ordered_region_id = OrderedRegion.objects.filter(start_id= start_id, end_id= end_id).first().id
        res['code'] = 200
        res['data'] = OrderSer(Order.objects.filter(ordered_region_id= ordered_region_id, result__in=['完成', '退回']), many=True).data
        return Response(res)

# 地区选项加载
class RegionOption(APIView):
    # 发货地加载
    def get(self, request):
        res = {}
        # 先根据权限形成json
        if 1 in getRights(request):
            r_data = OrderedRegion.objects.all()
        else:
            office_id = getOffice(request).get('id')
            r_data = OrderedRegion.objects.filter(office_id= office_id)
        r_json = OrderedRegionSer(r_data, many=True).data
        final_list = []
        for r in r_json:
            r_element = {'children':[]}
            p_code = r.get('start').get('upgrade')
            r_element['value'] = p_code
            exist = 0
            for f in final_list:
                if p_code == f.get('value'):
                    r_element = f
                    exist = 1
                    break
            c_code = r.get('start').get('code')
            city = r.get('start').get('region')
            c_dict = {'value':c_code, 'label': city}
            if not c_dict in r_element['children']:
                r_element['children'].append(c_dict)
            if exist == 0:
                reg = Region.objects.filter(code=p_code, upgrade__isnull=True).first()
                r_element['label'] =reg.region
                final_list.append(r_element)
        print(final_list)
        res['code'] = 200
        res['data'] = final_list
        return Response(res)
    # 收货地加载
    def post(self, request):
        res = {}
        send = request.data.get('send')
        print(send)
        # 获取id
        r_id = Region.objects.filter(code= send[1], upgrade= send[0]).first()
        # 获取关系表
        r_data = OrderedRegion.objects.filter(start_id= r_id.id)
        r_json = OrderedRegionSer(r_data, many=True).data
        final_list = []
        for r in r_json:
            print(r)
            r_element = {'children':[]}
            p_code = r.get('end').get('upgrade')
            r_element['value'] = p_code
            exist = 0
            for f in final_list:
                if p_code == f.get('value'):
                    r_element = f
                    exist = 1
                    break
            c_code = r.get('end').get('code')
            city = r.get('end').get('region')
            c_dict = {'value':c_code, 'label': city}
            if not c_dict in r_element['children']:
                r_element['children'].append(c_dict)
            if exist == 0:
                reg = Region.objects.filter(code=p_code, upgrade__isnull=True).first()
                r_element['label'] =reg.region
                final_list.append(r_element)
        print(final_list)
        res['code'] = 200
        res['data'] = final_list
        return Response(res)

# 货物线路分析
class AnalysisAdmin(APIView):
    def get(self, request):
        res = {}
        return Response(res)


# 路线
class PathAdmin(APIView):
    def get(self, request):
        res = {}
        location_list = []
        if request.GET.get('start') and request.GET.get('end'):
            for i in request.GET.values():
                geo = requests.get('https://restapi.amap.com/v3/geocode/geo?address=%s&output=JSON&key=5e5314fd7867bae494566df784aee47c'%i).json()
                if (geo.get('geocodes')) == 0:
                    print('跳出循环')
                    return HttpResponse('http://qakgy27pn.bkt.clouddn.com/path.png')
                else:
                    location_list.append(geo.get('geocodes')[0].get('location'))
            zoom = locational(location_list)
            img = requests.get('https://restapi.amap.com/v3/staticmap?zoom=%s&size=750*750&paths=10,0x0000ff,1,,:%s;%s&key=5e5314fd7867bae494566df784aee47c'%(zoom, location_list[0], location_list[1]))
        else:
            img = 'http://qakgy27pn.bkt.clouddn.com/path.png'
        return HttpResponse(img)


# 订单管理
class OrderAdmin(APIView):
    def get(self, request):
        res = {}
        print(getRights(request))
        if 1 in getRights(request):
            res['data'] = OrderSer(Order.objects.all(), many=True).data
        else:
            customs = Custom.objects.filter(office_id=getOffice(request).get('id'))
            customs_data = CustomSer(customs, many=True).data
            customs_iter = map(lambda x:int(x.get('id')), customs_data)
            c_list = list(customs_iter)
            data = OrderSer(Order.objects.filter(custom_id__in= c_list), many=True).data
            res['data'] = data
        res['code'] = 200
        return Response(res)
    def post(self, request):
        res = {}
        data = request.data
        try:
            print('='*100)
            # 获取坐标
            start = requests.get(
                'https://restapi.amap.com/v3/geocode/geo?address=%s&output=JSON&key=5e5314fd7867bae494566df784aee47c' % data.get('origin')).json().get('geocodes')[0]
            print(start)
            start_location = start.get('location')
            start_code = start.get('adcode')[0:4]
            cunstom_add = Custom.objects.get(id= data['custom']).address
            print(cunstom_add)
            end = requests.get(
                'https://restapi.amap.com/v3/geocode/geo?address=%s&output=JSON&key=5e5314fd7867bae494566df784aee47c' % cunstom_add).json().get('geocodes')[0]
            end_location = end.get('location')
            print(end_location)
            end_code = end.get('adcode')[0:4]
            order = Order(
                equipment_id= data['equipment'],
                order= data['order'],
                low_temp= data['low_temp'],
                high_temp= data['high_temp'],
                result= '未开启',
                custom_id= data['custom'],
                origin = data['origin'],
                start_location= start_location,
                end_location= end_location,
            )
            office_id = getOffice(request).get('id')
            # 获取start_id 和end_id
            start_id = Region.objects.filter(code= start_code[2:4], upgrade=start_code[0:2]).first().id
            end_id = Region.objects.filter(code= end_code[2:4], upgrade=end_code[0:2]).first().id
            # 排重
            print(start_id)
            print(end_id)
            org = OrderedRegion.objects.filter(start_id= start_id, end_id= end_id, office_id= office_id).first()
            if not org:
                org = OrderedRegion(start_id= start_id, end_id= end_id, office_id= office_id)
                org.save()
            print(org.id)
            order.ordered_region_id = org.id
            order.save()
            for i in data['type']:
                order.type.add(Type.objects.get(id=i))
            res['code'] = 200
            res['message'] = '添加成功'
        except Exception as e:
            res['code'] = 403
            res['message'] = '参数错误'
        return Response(res)


# 设备管理
class EquipmentAdmin(APIView):
    def get(self, request):
        res = {}
        res['code'] = 200
        res['data'] = EquipmentSer(Equipment.objects.all(), many=True).data
        return Response(res)


# 客户管理
class CustomAdmin(APIView):
    def get(self, request):
        res = {}
        if 1 in getRights(request):
            res['data'] = CustomSer(Custom.objects.all(), many=True).data
        else:
            res['data'] = CustomSer(Custom.objects.filter(office_id=getOffice(request).get('id')), many=True).data
        res['code'] = 200
        return Response(res)

    def post(self, request):
        res = {}
        data = request.data
        oid = data.get('office')
        try:
            Custom(
                custom=data.get('custom'),
                address=data.get('address'),
                phone=data.get('phone'),
                phone2=data.get('phone2'),
                name=data.get('name'),
                office=Office.objects.get(id=oid),
            ).save()
            res['code'] = 200
            res['message'] = '添加成功'
        except Exception as e:
            print(e)
            res['code'] = 403
            res['message'] = '参数不正确'
        return Response(res)


# 货物类型管理
class TypeAdmin(APIView):
    def get(self, request):
        res = {}
        print('-' * 100)
        # 获取用户权限
        right = getRights(request)
        if 1 in right:
            res['data'] = TypeSer(Type.objects.all(), many=True).data
        else:
            office_id = getOffice(request).get('id')
            print(office_id)
            res['data'] = TypeSer(Type.objects.filter(office_id=office_id), many=True).data
        res['code'] = 200
        return Response(res)

    def post(self, request):
        res = {}
        data = request.data
        print(data)
        # 货物类型信息
        type_data = data.get('type')
        uid = getID(request)
        type_data['office'] = OfficeSer(User.objects.get(id=uid).office).data.get('id')
        print(type_data)
        type_ser = TypeSer(data=type_data)
        if type_ser.is_valid():
            type_ser.save()
        alert_data = data.get('alert')
        print(type_ser.data)
        for i in alert_data:
            if i['mode'] == 1:
                Alert(alert='报警设置-主报警器%s' % i['id'], high_alert=i['high'], threshold=i['threshold'],
                      type_id=type_ser.data.get('id')).save()
            elif i['mode'] == 2:
                Alert(alert='报警设置-主报警器%s' % i['id'], low_alert=i['low'], threshold=i['threshold'],
                      type_id=type_ser.data.get('id')).save()
            elif i['mode'] == 3:
                Alert(alert='报警设置-主报警器%s' % i['id'], high_alert=i['high'], low_alert=i['low'], threshold=i['threshold'],
                      type_id=type_ser.data.get('id')).save()
        res['code'] = 200
        res['message'] = '添加成功'
        return Response(res)
